package com.rongke.web.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.web.heepay.GetToken;
import com.rongke.web.heepay.PayConfirm;
import com.rongke.web.heepay.model.HeepayNotify;
import com.rongke.web.heepay.model.QuickPayRequest;
import com.rongke.model.BankcardInfo;
import com.rongke.model.CapitalDetailed;
import com.rongke.model.User;
import com.rongke.model.UserAccount;
import com.rongke.redis.RedisClusterCache;
import com.rongke.service.BankcardInfoService;
import com.rongke.service.CapitalDetailedService;
import com.rongke.service.UserAccountService;
import com.rongke.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @UserAccountController
 * @Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/userAccount")
@Transactional
@CrossOrigin
public class UserAccountController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private UserService userService;
    @Autowired
    private CapitalDetailedService capitalDetailedService;
    @Autowired
    private BankcardInfoService bankcardInfoService;
    @Autowired
    private RedisClusterCache redisClusterCache;
    /**
     * @添加
     * @param userAccount
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addUserAccount(@RequestBody UserAccount userAccount){
        log.debug("添加");
        userAccountService.insert(userAccount);
        return JsonResp.ok(userAccount);
    }

    /**
     * @修改
     * @param userAccount
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateUserAccount(@RequestBody UserAccount userAccount){
        log.debug("修改");
        userAccountService.updateById(userAccount);
        return JsonResp.ok(userAccount);
    }
    /**
     * @根据id查找
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectUserAccount(Long id){
        log.debug("查找");
        UserAccount userAccount = userAccountService.selectById(id);
        return JsonResp.ok(userAccount);
    }

    /**
     * @备注：用户充值
     * @param bankCardInfoId
     * @param money
     * @return
     */
    @RequestMapping(value = "/charge",method = RequestMethod.GET)
    public JsonResp charge(Long bankCardInfoId, Float money, HttpServletRequest request){
        String remoteAddr = "";
        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }
        System.out.println(remoteAddr);



        User loginUser = userService.findLoginUser();
        /*EntityWrapper<UserAccount> accountEntityWrapper = new EntityWrapper<>();
        accountEntityWrapper.eq("user_id",loginUser.getId());
        UserAccount userAccount = userAccountService.selectOne(accountEntityWrapper);
        userAccount.setMoney(userAccount.getMoney()+money);*/
        CapitalDetailed capitalDetailed = new CapitalDetailed();
        capitalDetailed.setCreateDatetime(new Date());
        capitalDetailed.setMoney(money);
        capitalDetailed.setUserId(loginUser.getId());
        capitalDetailed.setType(0);
        capitalDetailed.setBankCardInfo(bankCardInfoId);

        boolean insert = capitalDetailedService.insert(capitalDetailed);
        if (insert){
            EntityWrapper<BankcardInfo> bankcardInfoEntityWrapper = new EntityWrapper<>();
            bankcardInfoEntityWrapper.eq("id",bankCardInfoId);
            BankcardInfo bankcardInfo = bankcardInfoService.selectOne(bankcardInfoEntityWrapper);
            QuickPayRequest quickPayRequest = new QuickPayRequest();
            quickPayRequest.setBankCardInfo(bankcardInfo.getRealName()+"^"+bankcardInfo.getBankNum()+"^"+bankcardInfo.getIdCard()+"^"+loginUser.getPhone());//郭新胜^6230520320015163975^130323199407125632^18324465241"
            quickPayRequest.setDescription("charge");

            if (bankcardInfo.getHyAuthCode()==null){
                quickPayRequest.setHyAuthCode("");
            }else {
                quickPayRequest.setHyAuthCode(bankcardInfo.getHyAuthCode());
            }
            quickPayRequest.setPayAmount(money.toString());
            quickPayRequest.setMerchantOrderNo(capitalDetailed.getId().toString());
            quickPayRequest.setMerchantUserName(loginUser.getUserName());
            quickPayRequest.setRequestUserIp(remoteAddr);
            quickPayRequest.setMerchantUserId(loginUser.getId().toString());
            quickPayRequest.setMerchantUserName("");
            String ret = GetToken.getToken(quickPayRequest);
            if ("{\"retMsg\":\"返回数据验签失败\"}".equals(ret)){
                return JsonResp.fa(ret);
            }
            JSONObject retJson = JSONObject.parseObject(ret);
            Integer retCode = retJson.getInteger("retCode");
            if (retCode==1){
                String token = retJson.getString("token");
                redisClusterCache.putCacheWithExpireTime("token"+loginUser.getId(),token,5*60);
                boolean b = capitalDetailedService.insert(capitalDetailed);
                if (b){
                    return JsonResp.ok(ret);
                }
            }
            return JsonResp.fa(ret);
        }

        return JsonResp.fa("充值失败");
    }

    /**
     * @备注:用户充值确认
     * @param msgCode
     * @param request
     * @return
     */
    @RequestMapping(value = "/confirmCharge",method = RequestMethod.GET)
    public JsonResp confirmCharge(String msgCode,HttpServletRequest request){
        String remoteAddr = "";
        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }
        User loginUser = userService.findLoginUser();
        String ret = PayConfirm.getToken(msgCode, remoteAddr, "", (String) redisClusterCache.getCache("token" + loginUser.getId()));
        if ("{\"retMsg\":\"返回数据验签失败\"}".equals(ret)){
            return JsonResp.fa(ret);
        }
        JSONObject retJson = JSONObject.parseObject(ret);
        Integer retCode = retJson.getInteger("retCode");
        String resultCode = retJson.getString("result");
        if (retCode == 1&&"1000".equals(resultCode)){
            Long orderNo = retJson.getLong("merchantOrderNo");
            String hyAuthCode = retJson.getString("hyAuthCode");

            EntityWrapper<CapitalDetailed> capitalDetailedEntityWrapper = new EntityWrapper<>();
            capitalDetailedEntityWrapper.eq("id",orderNo);
            CapitalDetailed capitalDetailed = capitalDetailedService.selectOne(capitalDetailedEntityWrapper);
            EntityWrapper<BankcardInfo> bankcardInfoEntityWrapper = new EntityWrapper<>();
            bankcardInfoEntityWrapper.eq("id",capitalDetailed.getBankCardInfo());
            BankcardInfo bankcardInfo = bankcardInfoService.selectOne(bankcardInfoEntityWrapper);
            String hyAuthCode1 = bankcardInfo.getHyAuthCode();
            if (StringUtils.isEmpty(hyAuthCode1)){
                bankcardInfo.setHyAuthCode(hyAuthCode);
                bankcardInfoService.updateById(bankcardInfo);
            }
            Integer type = capitalDetailed.getType();
            if (type == 1){
                return JsonResp.ok("充值成功");
            }
            capitalDetailed.setType(8);
            boolean b = capitalDetailedService.updateById(capitalDetailed);
            if (b){
                return JsonResp.ok(ret);
            }
        }
        return JsonResp.fa(ret);
    }



    @RequestMapping(value = "/receiveNotify",method = RequestMethod.POST)
    public @ResponseBody String notifyok(@RequestBody HeepayNotify heepayNotify) {
        //商户业务处理
        if ("1000".equals(heepayNotify.getResult())){
            Long merchantOrderNo = heepayNotify.getMerchantOrderNo();
            EntityWrapper<CapitalDetailed> capitalDetailedEntityWrapper = new EntityWrapper<>();
            capitalDetailedEntityWrapper.eq("id",capitalDetailedEntityWrapper);
            CapitalDetailed capitalDetailed = capitalDetailedService.selectOne(capitalDetailedEntityWrapper);
            if (capitalDetailed.getType()!= 1 ){
                capitalDetailed.setType(1);
                capitalDetailedService.updateById(capitalDetailed);
                EntityWrapper<UserAccount> userAccountEntityWrapper = new EntityWrapper<>();
                userAccountEntityWrapper.eq("user_id",capitalDetailed.getUserId());
                UserAccount userAccount = userAccountService.selectOne(userAccountEntityWrapper);
                userAccount.setMoney(userAccount.getMoney()+heepayNotify.getSuccessAmount());
                boolean b = userAccountService.updateById(userAccount);
                if (b){
                    return "ok";
                }
            }
        }
        return "fa";
    }


    /**
     * @备注：查询用户余额
     * @return
     */
    @RequestMapping(value = "/showAccount",method = RequestMethod.GET)
    public JsonResp showAccount(){
        User loginUser = userService.findLoginUser();
        System.out.println("用户："+loginUser);
        EntityWrapper<UserAccount> userAccountEntityWrapperr = new EntityWrapper<>();
        userAccountEntityWrapperr.eq("user_id",loginUser.getId());
        UserAccount userAccount = userAccountService.selectOne(userAccountEntityWrapperr);
        return JsonResp.ok(userAccount);
    }

    /**
     * @备注:用户显示资金明细
     * @return
     */
    @RequestMapping(value = "/showCapitalDetailed",method = RequestMethod.GET)
    public JsonResp showCapitalDetailed(){
        User loginUser = userService.findLoginUser();
        EntityWrapper<CapitalDetailed> capitalDetailedEntityWrapper = new EntityWrapper<>();
        capitalDetailedEntityWrapper.eq("user_id",loginUser.getId());
        capitalDetailedEntityWrapper.orderBy("create_datetime",false);
        List<CapitalDetailed> capitalDetaileds = capitalDetailedService.selectList(capitalDetailedEntityWrapper);
        if (capitalDetaileds.size()>0){
            return JsonResp.ok(capitalDetaileds);
        }
        return JsonResp.fa("没有资金明细信息");
    }

    /**
     * 用户显示充值信息
     * @return
     */
    @RequestMapping(value = "showChargeInfo",method = RequestMethod.GET)
    public JsonResp showChargeInfo(){
        User loginUser = userService.findLoginUser();
        EntityWrapper<CapitalDetailed> capitalDetailedEntityWrapper = new EntityWrapper<>();
        capitalDetailedEntityWrapper.eq("user_id",loginUser.getId());
        Integer[] types = {1,0,6,8};
        capitalDetailedEntityWrapper.in("type",types);
        capitalDetailedEntityWrapper.orderBy("create_datetime",false);
        List<CapitalDetailed> capitalDetaileds = capitalDetailedService.selectList(capitalDetailedEntityWrapper);
        if (capitalDetaileds.size()>0){
            return JsonResp.ok(capitalDetaileds);
        }
        return JsonResp.fa("没有充值信息");
    }

    @RequestMapping(value = "showWithdrawalsInfo",method = RequestMethod.GET)
    public JsonResp showWithdrawalsInfo(){
        User loginUser = userService.findLoginUser();
        EntityWrapper<CapitalDetailed> capitalDetailedEntityWrapper = new EntityWrapper<>();
        capitalDetailedEntityWrapper.eq("user_id",loginUser.getId());
        Integer[] types = {4,5,7};
        capitalDetailedEntityWrapper.in("type",types);
        capitalDetailedEntityWrapper.orderBy("create_datetime",false);
        List<CapitalDetailed> capitalDetaileds = capitalDetailedService.selectList(capitalDetailedEntityWrapper);
        if (capitalDetaileds.size()>0){
            return JsonResp.ok(capitalDetaileds);
        }
        return JsonResp.fa("没有提现信息");

    }

    @RequestMapping(value = "withdrawals",method = RequestMethod.GET)
    public JsonResp withdrawals(Integer bankCardInfoId,Float money ){

        return JsonResp.ok("");
    }
}
